<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyNewProductsSizeTable;
use App\Http\Models\Mysql\StyleTable;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class pullNewProducts extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:pullNewProducts {--type_no=}';

    /**
     * The console command description.
     * 0 /1 * * *
     * @var string
     */
    protected $description = '同步尺寸表--设计档案';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $autoKey = "auto_pullNewProducts";
        Cache::put($autoKey, 1, Carbon::now()->addMinutes(15));
        $typeNo = $this->option('type_no') ?: "";
        $conn = (new StyleTable());
        if(!empty($typeNo)){
            $typeNos = explode(",", $typeNo);
            $conn = $conn->whereIn('number', $typeNos);
        }else{
            $time = strtotime(date('Y-m-d 00:00:00', strtotime('- 3 day'))) - 1512460800;
            $conn = $conn->where('creation_time', '>=', $time);
        }
        $styleList = $conn->get()->toArray();
        $total = count($styleList);
        $num = 1;
        foreach ($styleList as $style){
            $exist = (new SsyNewProductsSizeTable())->where('type_no', $style['number'])->exists();
            echo "共[{$total}, {$num}], 正在执行: {$style['number']}, ".($exist ? "已存在\n" : "新增中...");
            $num++;
            if($exist){
                continue;
            }
            $data = [
                "type_no" => $style['number'],//款号
                "type_name" => $style['name'],//款名
                "publisher" => $style['paper_designer'],//版师
                "createtime" => date('Y-m-d H:i:s'),
            ];
            $res = (new SsyNewProductsSizeTable())->createData($data);
            if($res['id'] ?? ""){
                echo "新增成功 \n";
            }else{
                echo "新增失败：".$res['msg']."\n";
            }
        }
        Cache::forget($autoKey);
    }
}
